package com.hao.tool.util.module.base.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.hao.tool.common.entity.LayResponse;
import com.hao.tool.common.security.CookieUtil;
import com.hao.tool.common.security.JwtConstant;
import com.hao.tool.common.security.JwtInfo;
import com.hao.tool.common.security.JwtUtil;
import com.hao.tool.util.component.properties.PropertiesInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * description
 *
 * @author RuiHaoZ on GZ.cmhk
 * @date 2019-11-22 23:37
 */
@RestController
@RequestMapping("/rest/base")
public class BaseRestController {

    @Autowired
    private PropertiesInfo propertiesInfo;
    private Logger logger = LoggerFactory.getLogger(BaseRestController.class);

    @GetMapping("/qr")
    public void buildQr(String content, HttpServletResponse response) {
        byte[] bytes = QrCodeUtil.generatePng(content, 300, 300);
        try (OutputStream outputStream = response.getOutputStream()) {
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    @PostMapping("/login")
    public LayResponse login(String authUserCode, HttpServletResponse response) {
        logger.info("用户：{} 尝试登陆", authUserCode);
        Map<String, String> userMap = new HashMap<>();
        if (StringUtils.isNotBlank(propertiesInfo.getUserAuthCode())) {
            for (String authUser : propertiesInfo.getUserAuthCode().split(",")) {
                userMap.put(authUser, "");
            }
        }
        if (userMap.containsKey(authUserCode)) {
            JwtInfo jwtInfo = JwtInfo.build("jti-" + authUserCode, authUserCode, JwtConstant.DAY_1, null);
            String accessToken = JwtUtil.buildToken(jwtInfo);
            jwtInfo.setJwtStr(accessToken);
            CookieUtil.saveCookie(response, JwtConstant.COOKIE_NAME, accessToken);
            return LayResponse.builder().code(200).data(jwtInfo).build();
        } else {
            CookieUtil.saveCookie(response, JwtConstant.COOKIE_NAME, "accessToken");

            return LayResponse.builder().code(400).msg("授权码不存在").build();

        }
    }
}
